﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.Caching;
using MySQL.Db;

namespace Gollie.DataTables
{
	public class VendorTransactionsItem
	{
		public DateTime Dag { get; set; }
		public decimal Bedrag { get; set; }
		public string DagString { get; set; }
	}

	public class VendorTransactions : BaseBindable<VendorTransactionsItem>
	{
		public Dictionary<DateTime, TransactionHistory> Transactions = new Dictionary<DateTime, TransactionHistory>();

		public VendorTransactions(uint vendorId, DateTime from, DateTime to)
		{
			to = to.AddDays(1);

			ResultSet resultSet = Database.Queries.GetVendorTransactions(vendorId, from, to);

			this.AddDetails(resultSet, from, to);
		}

		private void AddDetails(ResultSet resultSet, DateTime from, DateTime to)
		{
			int numRows = resultSet.Count;
			if (numRows == 0)
			{
				this.AddZeroRows(from, to);

				return;
			}

			TransactionHistory history = new TransactionHistory();

			DateTime purchaseDate = resultSet.GetDateTime(0, "purchasedate");
			DateTime currentDay = purchaseDate.Date;

			this.AddZeroRows(from, currentDay);

			decimal saldo = resultSet.GetDecimal(0, "amount");
			history.AddDetails(purchaseDate, saldo);

			for (int i = 1; i < numRows; i++)
			{
				purchaseDate = resultSet.GetDateTime(i, "purchasedate");
				decimal amount = resultSet.GetDecimal(i, "amount");
				DateTime nextDay = purchaseDate.Date;

				if (nextDay == currentDay)
				{
					history.AddDetails(purchaseDate, amount);
				}
				else
				{
					this.CreateRow(currentDay, history.Total);

					this.AddZeroRows(currentDay.AddDays(1), nextDay);

					this.Transactions[currentDay] = history;
					currentDay = nextDay;
					history = new TransactionHistory();
					history.AddDetails(purchaseDate, amount);
				}
			}

			this.Transactions[currentDay] = history;

			this.CreateRow(currentDay, history.Total);

			this.AddZeroRows(currentDay.AddDays(1), to);
		}

		private void CreateRow(DateTime currentDay, decimal sum)
		{
			this.Add(new VendorTransactionsItem()
			{
				Dag = currentDay,
				Bedrag = sum,
				DagString = currentDay.ToString("ddMMyyyy")
			});
		}

		private void AddZeroRows(DateTime from, DateTime to)
		{
			while (from < to)
			{
				this.Transactions[from] = new TransactionHistory();
				this.CreateRow(from.Date, 0);
				from = from.AddDays(1);
			}
		}

		public decimal Sum()
		{
			return this.Sum(item => item.Bedrag);
		}
	}
}